package com.example.myapplication16_2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    // 服务器IP地址和端口
    private static final String SERVER_IP = "192.168.2.51"; // 模拟器连接本机服务器的IP地址
    private static final int SERVER_PORT = 9999;

    // 界面控件
    private ListView chatListView;
    private EditText edtMsg;
    private Button btnSend;

    // 网络通信相关
    private Socket socket;
    private PrintWriter writer;
    private BufferedReader reader;

    // 消息列表和适配器
    private List<String> messageList = new ArrayList<>();
    private ArrayAdapter<String> adapter;

    // 处理收到的消息并更新UI
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            // 将收到的消息添加到列表并刷新ListView
            String message = (String) msg.obj;
            messageList.add(message);
            adapter.notifyDataSetChanged();
            // 滚动到最新消息
            chatListView.setSelection(messageList.size() - 1);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化控件
        chatListView = findViewById(R.id.chatListView);
        edtMsg = findViewById(R.id.edt_msg);
        btnSend = findViewById(R.id.btn_send);

        // 设置ListView的适配器
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, messageList);
        chatListView.setAdapter(adapter);

        // 创建并启动网络连接线程
        new Thread(new ClientThread()).start();
    }

    // 发送消息按钮点击事件
    public void sendMsg(View view) {
        final String message = edtMsg.getText().toString().trim();
        if (message.isEmpty()) {
            Toast.makeText(this, "消息不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建线程发送消息
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (writer != null) {
                    writer.println(message);
                    // 清空输入框
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            edtMsg.setText("");
                        }
                    });
                }
            }
        }).start();
    }

    // 客户端网络连接线程
    private class ClientThread implements Runnable {
        @Override
        public void run() {
            try {
                // 连接服务器
                socket = new Socket(SERVER_IP, SERVER_PORT);
                // 创建输出流，明确使用UTF-8编码
                writer = new PrintWriter(
                    new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8), true);
                // 创建输入流，明确使用UTF-8编码
                reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));

                // 连接成功，添加提示消息
                Message connMsg = new Message();
                connMsg.obj = "已连接到服务器";
                handler.sendMessage(connMsg);

                // 循环读取服务器发来的消息
                String message;
                while ((message = reader.readLine()) != null) {
                    Message msg = new Message();
                    msg.obj = message;
                    handler.sendMessage(msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
                // 连接失败，添加提示消息
                Message errorMsg = new Message();
                errorMsg.obj = "连接服务器失败：" + e.getMessage();
                handler.sendMessage(errorMsg);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 断开连接并释放资源
        try {
            if (writer != null) writer.close();
            if (reader != null) reader.close();
            if (socket != null) socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}